<?php

namespace app\models;

use yii\behaviors\TimestampBehavior;
use yii\data\ArrayDataProvider;
use yii\data\Pagination;
use yii\db\Exception;

/**
 * This is the model class for table "{{%contacts}}".
 *
 * @property int $id 联系人id
 * @property int $customer_id 客户ID
 * @property string $name 联系人姓名
 * @property int $sex 性别:1男，2女
 * @property string|null $role 角色
 * @property string $mobile 手机
 * @property int $created_by 创建者uid
 * @property int $created_at 创建时间
 * @property int $updated_by 更新人
 * @property int $updated_at 信息更新时间
 * @property int $is_deleted 是否被删除
 * @property int $deleted_by 删除人
 * @property int $deleted_at 删除时间
 */
class Contacts extends ActiveRecord
{

    public function behaviors()
    {
        return [['class' => TimestampBehavior::class]];
    }

    public static function tableName()
    {
        return '{{%contacts}}';
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                $this->created_by = $this->updated_by = user()->id;
                $this->deleted_at = 0;
                $this->deleted_by = 0;
            } else {
                $this->updated_by = user()->id;
            }
            return true;
        }
        return false;
    }

    public function rules()
    {
        return [
            [
                [
                    'name',
                    'role',
                    'mobile',
                    'created_by',
                    'mobile',
                    'customer_id',
                    'sex',
                    'created_by',
                    'created_at',
                    'updated_by',
                    'updated_at',
                    'is_deleted',
                    'deleted_by',
                    'deleted_at'
                ],
                'safe'
            ],
        ];
    }

    public static function performCreate($contact, $data)
    {
        $db = app()->db;
        $trans = $db->beginTransaction();
        try {

            $model = new self();
            $model->setAttributes($contact);
            $model->save(false);

            $data['contacts_id'] = $model->id;
            ContactsData::newCreate($data);

            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            dump($e->getMessage());
        }
    }

    public static function performUpdate($id, $contact, $data)
    {
        $db = app()->db;
        $trans = $db->beginTransaction();
        try {
            self::updateByPk($contact, $id);
            ContactsData::updateByPk($data, $id);
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            dump($e->getMessage());
        }
    }

    public function attributeLabels()
    {
        return [
            'id' => '联系人id',
            'customer_id' => '客户ID',
            'name' => '联系人姓名',
            'sex' => '性别:1男，2女',
            'role' => '角色',
            'mobile' => '手机',
            'created_by' => '创建者uid',
            'created_at' => '创建时间',
            'updated_by' => '更新人',
            'updated_at' => '信息更新时间',
            'is_deleted' => '是否被删除',
            'deleted_by' => '删除人',
            'deleted_at' => '删除时间',
        ];
    }

    public static function columns()
    {
        return [
            'customer_id',
            'name',
            'sex',
            'role',
            'mobile',
            'created_by',
            'created_at',
            'updated_by',
            'updated_at',
            'is_deleted',
            'deleted_by',
            'deleted_at',
        ];
    }

    public static function getListBy($param)
    {
        $query = self::find()->alias('c');
        $query->select([
            'c.id',
            'c.name AS linkman',
            'c.role',
            'c.mobile',
            'cu.name AS username',
            'cu.id AS customerId',
            'u.username AS author',
            'FROM_UNIXTIME(c.created_at, "%Y-%m-%d %H:%i:%s") AS createdAt'
        ]);
        $query->leftJoin(Customer::tableName() . ' cu', 'cu.id = c.customer_id');
        $query->leftJoin(User::tableName() . ' u', 'u.id = c.created_by');
        $query->andWhere(['c.is_deleted' => 0]);
        $query->andFilterWhere(['c.customer_id' => $param['customerId']]);
        $query->andFilterWhere(['like', 'c.name', $param['customerId']]);
        $query->asArray();

        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $query->count()
        ]);

        $pagination->setPage(($param['page'] ?: 1) - 1);
        $pagination->setPageSize($param['pageSize'] ?: 10);

        $data = $query->offset($pagination->getOffset())
            ->orderBy('c.id DESC')
            ->limit($pagination->getLimit())->all();

        $dataProvider = new ArrayDataProvider([
            'models' => $data,
            'Pagination' => $pagination,
        ]);

        $pageSize = $pagination->getPageSize();
        $totalPage = $pagination->getPageCount();
        $totalCount = $pagination->totalCount;

        return [
            'contact' => $dataProvider->getModels(),
            'pageSize' => $pageSize,
            'totalPage' => $totalPage,
            'totalCount' => $totalCount
        ];
    }

}